import logging

def index(): 
    d('request',request.vars)
    
    #constants       
    DAILY_LIMIT = 5
    POINTS_FOR_A_WITNESS = 100
    POINTS_FOR_AN_ENCOURAGEMENT = 10
    FREE_POINTS_FOR_NEW_USER = 500
    
    #facebook vars
    login_url = facebook.get_require_facebook_login_url()
    user_name = facebook.get_facebook_user()
    first_name = str(user_name).split(' ')[0]
    uid = facebook.request.facebook.uid    

    d('uid',uid)
        
    #biblebeaters vars
    sent_message = False    
    first_login = False    
    my_points = 0
    activity_levels = ['on-the-shelf','spreading-gods-word','cant-hold-the-gospel-in']
    my_status = activity_levels[0]
    problem_sending_message = False    
    used_witness_quota = False    
    used_encouragement_quota = False
    attempted_witness = False
    attempted_encourage = False
    attempted_bless = False
    points_user = None
    history = None   
    friends_that_have_biblebeaters = []      
           
    #if not logged in    
    if not uid:        
        val = str(
            """<script>"""+
            """window.top.location = """ + 
            """"http://www.facebook.com/"""+
            """login.php?api_key=%s&canvas=1?v=1.0";"""%(facebook.api_key)+
            """</script>"""
        )
        d('login_url',val)
        return val
        
    #if logged in
    else:    
        points_user = db(db.user.fbuid == uid).select().first()
        points_user_id = None
        if points_user: 
            my_points = points_user.points if points_user.points else 0
            points_user_id = points_user.id
        else:
            my_points = FREE_POINTS_FOR_NEW_USER
            points_user_id = db.user.insert(fbuid=uid,points=my_points,last_activity_level=0)
            first_login = True
        
        permission = True
        
        if not points_user or not points_user.offline_access:
            if request.vars.fb_sig_expires == '0' and request.vars.fb_sig_session_key:
                db(db.user.fbuid==uid).update(offline_access=request.vars.fb_sig_session_key)
            else:
                permission = request.facebook(
                    method="auth_revokeExtendedPermission",
                    args={
                        "perm": 'offline_access',
                        "uid": uid
                    }
                )
                permission = False       
                
        if permission:
            permission = request.facebook(
                method="users_hasAppPermission",
                args={
                    "ext_perm": 'publish_stream',
                    "uid": uid
                }
            )
            if permission:
                permission = request.facebook(
                    method="users_hasAppPermission",
                    args={
                        "ext_perm": 'offline_access',
                        "uid": uid
                    }
                )
        
        if not permission:
            return  str(
                """<script>"""+
                """window.top.location = "http://www.facebook.com/"""+
                """connect/prompt_permissions.php"""+
                """?api_key=%s&v=1.0""" % request.facebook.api_key +
                """&next=http://apps.facebook.com/%s/"""%(request.facebook.app_name) +
                """%3fxxRESULTTOKENxx"""+
                """&ext_perm=publish_stream,offline_access";"""+
                """</script>"""
            )    
        

        action = request.vars.action
        to_name = request.vars.uid
        
        #build witnesses sent today
        recent_witnesses_sent = db((db.action.from_fbuid == uid)&(db.action.action_type == 'witness')).select(orderby=~db.action.created_on,limitby=(0, 20))
        witnesses_sent_today = 0

        for item in recent_witnesses_sent:
            if item.created_on.timetuple().tm_yday == datetime.now().timetuple().tm_yday:
                witnesses_sent_today += 1             
                
        #build encouragements sent today        
        recent_encouragements_sent = db((db.action.from_fbuid == uid)&(db.action.action_type == 'encouragement')).select(orderby=~db.action.created_on,limitby=(0, 20))
        encouragements_sent_today = 0

        for item in recent_encouragements_sent:
            if item.created_on.timetuple().tm_yday == datetime.now().timetuple().tm_yday:
                encouragements_sent_today += 1
        
        
        if witnesses_sent_today >= DAILY_LIMIT:
            used_witness_quota = True
                
        if encouragements_sent_today >= DAILY_LIMIT:
            used_encouragement_quota = True   
        
           
        try:
            to_fbuid = int(request.vars.chosen_user_id)
        except:
            to_fbuid = None
            
        witness_message = request.vars.witness_message
        encouragement_message = request.vars.encouragement_message
        bless_message = request.vars.bless_message
        
        if uid and action in ['witness','encourage','bless'] and to_name and to_fbuid:
            if action == 'witness':
                attempted_witness = True
            elif action == 'bless':
                attempted_bless = True
            else:
                attempted_encourage = True

            if witness_message and len(witness_message) <= 10000:
                if not used_witness_quota:
                    db.action.insert(action_type='witness', from_fbuid=uid, from_name=user_name, to_fbuid=to_fbuid, to_name=to_name, message=witness_message)
                    my_points += POINTS_FOR_A_WITNESS
                    db(db.user.fbuid == uid).update(points=my_points)
                    witnesses_sent_today += 1
                    sent_message = True
            
            elif encouragement_message and len(encouragement_message) <= 10000:
                if not used_encouragement_quota:
                    db.action.insert(action_type='encouragement', from_fbuid=uid, from_name=user_name, to_fbuid=to_fbuid, to_name=to_name, message=encouragement_message)
                    my_points += POINTS_FOR_AN_ENCOURAGEMENT
                    db(db.user.fbuid == uid).update(points=my_points)                    
                    encouragements_sent_today += 1
                    sent_message = True
                    
            elif not bless_message or (bless_message and len(bless_message) <= 10000):
                gift = request.vars.gift
                if(gift=='flower' and my_points>=100)or(gift=='turtle' and my_points>=1000)or(gift=='car' and my_points>=10000):
                    db.action.insert(action_type='blessing', from_fbuid=uid, from_name=user_name, to_fbuid=to_fbuid, to_name=to_name, message='<img src="http://biblebeaters.salvationtek.com/home/static/gifts/'+gift+'.png" /><br/>'+str(bless_message or ''))
                    charge = 100
                    if gift == 'turtle': charge = 1000
                    elif gift == 'car' : charge = 10000                    
                    my_points -= charge
                    db(db.user.fbuid == uid).update(points=my_points)                    
                    sent_message = True
                    
                    
            if sent_message:
                try:
                    sent_action = 'a witness' 
                    if action == 'encourage': sent_action = 'an encouragement'
                    elif action == 'bless': sent_action = 'a blessing'
                    to_user = db(db.user.fbuid == to_fbuid).select().first()
                    message = "received %s from %s using BibleBeaters."%(sent_action,user_name)
                    import gluon.contrib.simplejson as simplejson
                    action_links = [{'text':'Open My BibleBeaters','href':'http://apps.facebook.com/biblebeaters/'}]
                    request.facebook(
                        method="stream_publish",
                        args={
                            "session_key":to_user.offline_access,
                            "message": message,
                            "action_links": simplejson.dumps(action_links),
                            "target_id": to_fbuid
                        }
                    )
                except Exception,details:
                    logging.error(details)
                    pass                        
    
            
        
        #build activity for this week
        activity_this_week = 1 if sent_message else 0

        activity = [item for item in recent_witnesses_sent]
        
        for item in recent_encouragements_sent: activity.append(item)
            
        for item in activity:
            if item.created_on.timetuple().tm_yday in range( datetime.now().timetuple().tm_yday - 6, datetime.now().timetuple().tm_yday + 1):
                activity_this_week += 1            

        d('activity_this_week',activity_this_week)
            
        if activity_this_week > 19:
            my_status = activity_levels[2]
        elif activity_this_week > 0:
            my_status = activity_levels[1]
        
        if points_user and activity_levels.index(my_status) != points_user.last_activity_level:
            
            #if there was a previous status
            if points_user and points_user.last_activity_level != None:                
                #send activity level change notification
                import gluon.contrib.simplejson as simplejson
                action_links = [{'text':'Login to BibleBeaters to View and Send messages.','href':'http://apps.facebook.com/biblebeaters/'}]                
                message='BibleBeaters activity level changed from %s to %s.'%(activity_levels[points_user.last_activity_level],my_status)
                action = [{'text':'Open My BibleBeaters','href':'http://apps.facebook.com/biblebeaters/'}]
                request.facebook(
                    method="stream_publish",
                    args={
                        "message": message,
                        "action_links": simplejson.dumps(action_links),                        
                        "uid": uid
                    }
                )
            
            db(db.user.fbuid == uid).update(last_activity_level=activity_levels.index(my_status))
        
        
        #do this again incase we just sent another message and the counter has changed
        if witnesses_sent_today >= DAILY_LIMIT:
            used_witness_quota = True
                
        if encouragements_sent_today >= DAILY_LIMIT:
            used_encouragement_quota = True   
            
        #load history    
        history_to_me = db(db.action.to_fbuid==uid).select()
        db(db.action.to_fbuid==uid).update(viewed=True)
        history_from_me = db(db.action.from_fbuid==uid).select()
        history = []
        for item in history_to_me:
            history.append(item)
        for item in history_from_me:
            history.append(item)
        
        import operator
        history.sort(key=operator.attrgetter('created_on'))
        history.reverse()
        
        rows = []
        
        for row in history:
            rows.append({
                "id":'row'+str(row.id),
                "action":row.action_type.capitalize() + " " + str("to" if str(uid) == str(row.from_fbuid) else "from"),
                "who":row.to_name if str(uid) == str(row.from_fbuid) else row.from_name,
                "when":str(row.created_on),#Helpers.prettydate(row.created_on)),
                "fromnow":str(Helpers.prettydate(row.created_on)),
                "viewed":"true" if row.viewed else "false",
                "message":str(row.message)
            })
        history = rows      
        
        #check if there were any problems
        if request.vars.action and not sent_message:
            problem_sending_message = True
                      
        #load the user's friends
        if points_user and points_user.offline_access:  
            friends_that_have_biblebeaters = request.facebook(
                method="friends_getAppUsers",
                args={
                    'session_key':points_user.offline_access,
                }
            )
    
        return dict(user_name=user_name,login_url=login_url,uid=uid,problem_sending_message=problem_sending_message,sent_message=sent_message,history=history,used_witness_quota=used_witness_quota,used_encouragement_quota=used_encouragement_quota,my_points=my_points,my_status=my_status,attempted_witness=attempted_witness,attempted_encourage=attempted_encourage,first_name=first_name,friends_that_have_biblebeaters=friends_that_have_biblebeaters)
